package org.jsola.hr.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsola.core.Page;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.ContractRechargeEnum;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.ISiteContractQuotaDAO;
import org.jsola.hr.dto.SiteContractQuotaAddDTO;
import org.jsola.hr.dto.SiteContractQuotaUpdateDTO;
import org.jsola.hr.entity.SiteContractQuotaDO;
import org.jsola.hr.query.SiteContractQuotaQuery;
import org.jsola.hr.service.ICompanyContractQuotaRecordService;
import org.jsola.hr.service.ISiteContractQuotaService;
import org.jsola.hr.vo.ContractRechargeVO;
import org.jsola.hr.vo.SiteContractQuotaVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 租户合同
 *
 * @author zhr
 */
@Slf4j
@Service("hrSiteContractQuotaServiceImpl")
public class SiteContractQuotaServiceImpl implements ISiteContractQuotaService {

    @Autowired
    private ISiteContractQuotaDAO siteContractQuotaDAO;

    @Autowired
    private ICompanyContractQuotaRecordService companyContractQuotaRecordService;


    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public SiteContractQuotaVO save(SiteContractQuotaAddDTO siteContractQuotaAddDTO, TokenUser tokenUser) {


        // 转DO
        SiteContractQuotaDO siteContractQuotaDO = siteContractQuotaAddDTO.to(SiteContractQuotaDO.class);
        // 保存
        siteContractQuotaDO = save(siteContractQuotaDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return siteContractQuotaDO.to(SiteContractQuotaVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(SiteContractQuotaUpdateDTO siteContractQuotaUpdateDTO, TokenUser tokenUser) {

        //转DO
        SiteContractQuotaDO siteContractQuotaDO = siteContractQuotaUpdateDTO.to(SiteContractQuotaDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(siteContractQuotaDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... siteContractQuotaIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) siteContractQuotaIds);
    }


    @Override
    public SiteContractQuotaVO selectById(String siteContractQuotaId, String siteId) {
        SiteContractQuotaDO siteContractQuotaDO = selectDOById(siteContractQuotaId, siteId);
        if (siteContractQuotaDO == null) {
            return null;
        }
        return siteContractQuotaDO.to(SiteContractQuotaVO.class);
    }


    @Override
    public List<SiteContractQuotaVO> select(SiteContractQuotaQuery siteContractQuotaQuery, String siteId) {
        List<SiteContractQuotaDO> siteContractQuotaDOList = selectDO(siteContractQuotaQuery, siteId);
        if (CollectionUtils.isEmpty(siteContractQuotaDOList)) {
            return siteContractQuotaDOList == null ? null : new ArrayList<>();
        }
        return siteContractQuotaDOList.stream()
                .map(siteContractQuotaDO -> siteContractQuotaDO.to(SiteContractQuotaVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(SiteContractQuotaQuery siteContractQuotaQuery, String siteId) {
        Example example = buildExample(siteContractQuotaQuery, siteId);
        return siteContractQuotaDAO.selectCountByExample(example);
    }

    @Override
    public Page<SiteContractQuotaVO> selectPage(SiteContractQuotaQuery siteContractQuotaQuery, String siteId) {
        Example example = buildExample(siteContractQuotaQuery, siteId);
        Page<SiteContractQuotaDO> page = siteContractQuotaDAO.selectPageByExample(example,
                siteContractQuotaQuery.getPageNo(),
                siteContractQuotaQuery.getPageSize());

        return page.to(SiteContractQuotaVO.class);
    }

    @Override
    public SiteContractQuotaDO selectDOById(String siteContractQuotaId, String siteId) {
        return listById(siteContractQuotaId, siteId);
    }

    @Override
    public List<SiteContractQuotaDO> selectDO(SiteContractQuotaQuery siteContractQuotaQuery, String siteId) {
        Example example = buildExample(siteContractQuotaQuery, siteId);
        return siteContractQuotaDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example
     *
     * @param siteContractQuotaQuery 查询参数
     * @param siteId                 所属站点id
     * @return example
     */
    private Example buildExample(SiteContractQuotaQuery siteContractQuotaQuery, String siteId) {
        Example example = new Example(SiteContractQuotaDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        // 排序
        ExampleKit.setExampleOrder(example, siteContractQuotaQuery.getOrders());
        return example;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public SiteContractQuotaVO saveOrUpdate(SiteContractQuotaUpdateDTO siteContractQuotaUpdateDTO, TokenUser tokenUser) {
        SiteContractQuotaDO siteContractQuotaDO = siteContractQuotaUpdateDTO.to(SiteContractQuotaDO.class);
        SiteContractQuotaDO siteContractQuotaDOTmp = selectDOBySiteId(tokenUser.getSiteId());

        if (StringUtils.isBlank(siteContractQuotaUpdateDTO.getId())) {
            //添加判断是否存在
            if (Objects.nonNull(siteContractQuotaDOTmp)) {
                return siteContractQuotaDOTmp.to(SiteContractQuotaVO.class);
            }
            // 保存
            siteContractQuotaDO = save(siteContractQuotaDO, tokenUser.getSiteId(), tokenUser.getUserId());
            return siteContractQuotaDO.to(SiteContractQuotaVO.class);
        } else {
            //编辑判断是否存在
            if (Objects.isNull(siteContractQuotaDOTmp)) {
                return null;
            }
            //根据主键更新，只更新非null值
            updateByIdSelective(siteContractQuotaDO, tokenUser.getSiteId(), tokenUser.getUserId());
            return siteContractQuotaDO.to(SiteContractQuotaVO.class);
        }
    }

    @Override
    public SiteContractQuotaDO selectDOBySiteId(String siteId) {
        Example example = new Example(SiteContractQuotaDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        return siteContractQuotaDAO.selectOneByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Integer rechargeSite(SiteContractQuotaUpdateDTO siteContractQuotaUpdateDTO, TokenUser tokenUser) {
        SiteContractQuotaVO vo = selectBySite(tokenUser.getSiteId());
        SiteContractQuotaDO quota = new SiteContractQuotaDO();
        if (vo == null) {
            quota.setContractCount(siteContractQuotaUpdateDTO.getCurrentContractCount());
            quota.setFaceCount(siteContractQuotaUpdateDTO.getCurrentFaceCount());
            quota.setContractSum(siteContractQuotaUpdateDTO.getCurrentContractCount());
            quota.setFaceSum(siteContractQuotaUpdateDTO.getCurrentFaceCount());
            this.save(quota, tokenUser.getSiteId(), tokenUser.getUserId());
        } else {
            quota.setId(vo.getId());
            quota.setContractCount(vo.getContractCount() + siteContractQuotaUpdateDTO.getCurrentContractCount());
            quota.setFaceCount(vo.getFaceCount() + siteContractQuotaUpdateDTO.getCurrentFaceCount());
            quota.setContractSum(vo.getContractSum() + siteContractQuotaUpdateDTO.getCurrentContractCount());
            quota.setFaceSum(vo.getFaceSum() + siteContractQuotaUpdateDTO.getCurrentFaceCount());
            //根据主键更新，只更新非null值
            updateByIdSelective(quota, tokenUser.getSiteId(), tokenUser.getUserId());
        }
        // 写入记录
        ContractRechargeVO recharge = new ContractRechargeVO();
        recharge.setCompanyId("system");
        recharge.setContractCount(siteContractQuotaUpdateDTO.getCurrentContractCount());
        recharge.setFaceCount(siteContractQuotaUpdateDTO.getCurrentFaceCount());
        recharge.setType(ContractRechargeEnum.SITE_RECHARGE.getValue());
        companyContractQuotaRecordService.addRecord(recharge, tokenUser);
        return 1;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Integer reduce(SiteContractQuotaUpdateDTO siteContractQuotaUpdateDTO, TokenUser tokenUser) {
        //  扣减租户份额
        siteContractQuotaDAO.add(-Math.abs(siteContractQuotaUpdateDTO.getCurrentContractCount()),
                -Math.abs(siteContractQuotaUpdateDTO.getCurrentFaceCount()), tokenUser.getSiteId());

        // 写入记录
        ContractRechargeVO recharge = new ContractRechargeVO();
        recharge.setCompanyId("system");
        recharge.setContractCount(siteContractQuotaUpdateDTO.getCurrentContractCount());
        recharge.setFaceCount(siteContractQuotaUpdateDTO.getCurrentFaceCount());
        recharge.setType(ContractRechargeEnum.PUBLISH_CONTRACT.getValue());
        companyContractQuotaRecordService.addRecord(recharge, tokenUser);
        return 0;
    }

    @Override
    public SiteContractQuotaVO selectBySite(String siteId) {
        Example example = new Example(SiteContractQuotaDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        SiteContractQuotaDO siteContractQuotaDO = siteContractQuotaDAO.selectOneByExample(example);
        if (siteContractQuotaDO == null) {
            SiteContractQuotaDO quota = new SiteContractQuotaDO();
            quota.setContractCount(0);
            quota.setFaceCount(0);
            quota.setContractSum(0);
            quota.setFaceSum(0);
            this.save(quota, siteId, UserContext.getUser().getUserId());
            return quota.to(SiteContractQuotaVO.class);
        }
        return siteContractQuotaDO.to(SiteContractQuotaVO.class);
    }

}




